--- 模块功能：电源管理
-- @author zgt
-- @module create
-- @license MIT
-- @copyright zgt
-- @release 2022-1-6
require "net"
require "pins"
module(..., package.seeall)

local prefix = "power"
-- 设置LCD驱动电压
pmd.ldoset(15, pmd.LDO_VLCD)
pmd.ldoset(15, pmd.LDO_VMMC)
pmd.ldoset(15, pmd.LDO_VSIM1)

--local p_master = pins.setup(13, 1)
-- local p_ready =  pins.setup(4, 1)
local p_resw1,sw1 = pins.setup(18, 0),0 -- 继电器1
local p_resw2,sw2= pins.setup(19, 0),0 -- 继电器2
local p_resw3,sw3 = pins.setup(23, 0),0 -- 继电器3
local p_resw4,sw4 = pins.setup(13, 0),0 -- 继电器4
local p_dc_out = pins.setup(5, 0) -- dc_out
--local p_dc_boost = pins.setup(23, 0) -- 升压
local SEL0= pins.setup(11)
local SEL1= pins.setup(10)
local SEL2= pins.setup(9)
-- adc
local adc_vbat_id = 2
local adc_ir = 3

-- 关闭总电源
function closeMaster()
    --p_master(0)
end
-- 锁定主电源
function openMasterLock()
    --p_master(1)
end
-- 打开输出 vbat
function openVout()
    p_dc_out(1)
end
function closeVout()
    p_dc_out(0)
end
-- 打开24V输出
function openBoost()
    --p_dc_boost(1)
end
function closeBoost()
    --p_dc_boost(0)
end
-- 打开继电器1
function openSW1()
    p_resw1(1)
    sw1=1
end
function closeSW1()
    p_resw1(0)
    sw1=0
end
function getSW1()
    return sw1
end
-- 打开继电器2
function openSW2()
    p_resw2(1)
    sw2=1
end
function closeSW2()
    p_resw2(0)
    sw2=0
end
function getSW2()
    return sw2
end
-- 打开继电器3
function openSW3()
    p_resw3(1)
    sw3=1
end
function closeSW3()
    p_resw3(0)
    sw3=0
end
function getSW3()
    return sw3
end
-- 打开继电器4
function openSW4()
    p_resw4(1)
    sw4=1
end
function closeSW4()
    p_resw4(0)
    sw4=0
end
function getSW4()
    return sw4
end
function getFlag()
    return ""..SEL2()..SEL1()..SEL0()
end
-- 电压adc通道电压读取
-- @id adc通道id 2:总电源
function getADC(id)
    adc.open(id)
    local adcValue, voltValue = adc.read(id)
    -- log.warn("power->",string.format("adc= %d,adcVal = %d,voltVal= %d",id,adcValue,voltValue))
    adc.close(id)
    if voltValue ~= 0xFFFF  then return voltValue end
    return 0
end
function getVbat( )
    return getADC(adc_vbat_id) * 11 / 1000
end
function getVI( )
    return getADC(adc_ir) * 11 / 1000
end
